<template>
  <div class="home">
    {{ classroom }}
  </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component';

// 案例: 创建一个教室类, 创建出来的对象都是可迭代对象
class Classroom {
  students
  constructor( students: string[]) {
    this.students = students
  }
  entry(newStudent: any): any {
    this.students.push(newStudent)
  }
  [Symbol.iterator]() {
    let index = 0
    return {
      next: () => {
        if (index < this.students.length) {
          return { done: false, value: this.students[index++] }
        } else {
          return {  done: true, value: undefined}
        }
      }
    }
  }
}


@Options({
  data() {
    return {
      classroom: []
    }
  },

  methods: {
    getObjValues () {
      /*
      Object.prototype[Symbol.iterator] = function (): any {
        console.log(Object.values(this))
        console.dir(Object.values(this)[Symbol.iterator])
        return Object.values(this)[Symbol.iterator]() // 调用数组的迭代器
      }
      */
    },

    // 生成迭代器方法
    createArrayIterator(arr: Array<any>) {
      let index = 0
      return {
        next: function() {
          if (index < arr.length) {
            return { done: false, value: arr[index++] }
          } else {
            return { done: true, value: undefined }
          }
        }
      }
    }
  },
  mounted() {
    const classroom = new Classroom( ["学生1", "学生2", "学生3", "学生4", "学生5"])
    classroom.entry("lilei")
    this.classroom = classroom.students

    console.log(classroom, 'classroom')
    for (const stu of classroom) {
      console.log(stu, 'stu')
    }

    this.getObjValues()
    // var [a, b] = {a: 1, b: 2}
    // console.log(a, b)

    const names = ["111", "222", "333"]
    const namesIterator = this.createArrayIterator(names)
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    console.log(namesIterator.next())
    // 打印
    // { done: false, value: '111' }
    // { done: false, value: '222' }
    // { done: false, value: '333' }
  }
})
export default class Home extends Vue {}
</script>
